package com.ruike.alisurface.printer;

import android.content.Context;
import android.content.res.AssetManager;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

import com.android.print.sdk.PrinterConstants;
import com.android.print.sdk.PrinterInstance;
import com.ruike.alisurface.utils.QrcodeUtils;

import java.io.IOException;
import java.io.InputStream;

/**
 * Author：voodoo
 * CreateTime：2021/7/26 14:01
 * Description：
 */
public class PrintUtils {

    public static volatile PrintUtils printUtils;
    private static final String SPLIT_LINE = "================================";

    public static PrintUtils getInstance() {
        if (printUtils == null) {
            synchronized (PrintUtils.class) {
                if (printUtils == null) {
                    printUtils = new PrintUtils();
                }
            }
        }
        return printUtils;
    }

    /**
     * 从Assets中读取图片
     */
    private Bitmap getImageFromAssetsFile(Context context, String fileName) throws IOException {
        Bitmap image = null;
        AssetManager am = context.getResources().getAssets();
        try {
            InputStream is = am.open(fileName);
            image = BitmapFactory.decodeStream(is);
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return image;
    }

    // ===================================================================================== 正式打印

    /**
     * 打印订单小票
     *
     * @param printer         打印机句柄
     * @param resources       资源对象，获取String使用
     * @param orderTicketBean 打印对象
     */
    public void printOrderTicket(PrinterInstance printer, Resources resources, OrderTicketBean.DataBean orderTicketBean) {
        printer.init();
        // 打印标题
        Object title = orderTicketBean.getDeviceName();
        if (title instanceof String) {
            setCentered(printer, true); // 居中放大
            printText(printer, title.toString());
        } else if (title instanceof Bitmap) {
            setCentered(printer, false); // 居中不放大
            printer.printImage((Bitmap) title);
        }
        recoverPrinter(printer); // 恢复左对齐

        // 打印基础数据
        printText(printer, String.format("机主电话：%s", orderTicketBean.getPhoneNumber()));
        printText(printer, String.format("购买日期：%s", orderTicketBean.getPayTime()));
        printText(printer, String.format("订单编号：%s", orderTicketBean.getOrderId()));
        printText(printer, SPLIT_LINE);

        // 打印药品详情
        for (OrderTicketBean.DataBean.ProductBeansBean productBean : orderTicketBean.getProductBeans()) {
            printText(printer, splicing(productBean.getProductName(), productBean.getSpecification()));
            printText(printer, splicing(productBean.getUnitPrice() + "", productBean.getNumber() + "", productBean.getSubtotal() + ""));
        }
        printText(printer, SPLIT_LINE);

        // 总计
        printText(printer, splicing("合计", orderTicketBean.getTotalPay() + ""));
        printText(printer, splicing("现金支付", orderTicketBean.getCash() + "", "医保支付", orderTicketBean.getMedicalInsurance() + ""));
        printText(printer, splicing("实收总计", orderTicketBean.getActualTotalPay() + ""));

        if (orderTicketBean.isIsPrintExhort() || orderTicketBean.isIsPrintQrCode()) {
            if (orderTicketBean.isIsPrintExhort()) {
                printText(printer, SPLIT_LINE);
                for (OrderTicketBean.DataBean.ExhortBeansBean exhortBean : orderTicketBean.getExhortBeans()) {
                    printText(printer, exhortBean.getProductName()); // 32
                    printText(printer, exhortBean.getDescribe()); // 32
                }
            }
            if (orderTicketBean.isIsPrintQrCode()) {
                printText(printer, SPLIT_LINE);
                setCentered(printer, false);
                Bitmap SnBitmap = QrcodeUtils.createQrCode(orderTicketBean.getQrcode(), 280, 280);
                printer.printImage(SnBitmap);
                printBlankLine(printer);
                printText(printer, orderTicketBean.getQrcodeDescribe()); // 32
            }
        }
        printBlankLine(printer);
        printBlankLine(printer);
    }

    /**
     * 设置居中
     *
     * @param mPrinter  打印机器
     * @param isEnlarge 是否放大
     */
    private static void setCentered(PrinterInstance mPrinter, boolean isEnlarge) {
        mPrinter.setPrinter(PrinterConstants.Command.ALIGN, PrinterConstants.Command.ALIGN_CENTER); // 居中
        if (isEnlarge) {
            mPrinter.setFont(1, 1, 0, 0); // 放大两倍 取值0到3对应放大1到4倍
        }
    }

    /**
     * 恢复打印机正常状态
     *
     * @param mPrinter 打印机器
     */
    private static void recoverPrinter(PrinterInstance mPrinter) {
        mPrinter.setPrinter(PrinterConstants.Command.ALIGN, PrinterConstants.Command.ALIGN_LEFT); // 左对齐
        mPrinter.setFont(0, 0, 0, 0); // 放大两倍 取值0到3对应放大1到4倍
    }

    /**
     * 最好不要超过32个字节
     *
     * @param connect 要打印的内容
     */
    private static void printText(PrinterInstance mPrinter, String connect) {
        mPrinter.printText(connect);
        printBlankLine(mPrinter);
    }

    /**
     * 走纸换行
     */
    private static void printBlankLine(PrinterInstance mPrinter) {
        mPrinter.setPrinter(PrinterConstants.Command.PRINT_AND_WAKE_PAPER_BY_LINE, 1); // 换1行
    }

    /**
     * 获取字符串占的位数
     *
     * @param content 内容
     * @return 长度
     */
    private static int getStringBite(String content) {
        char[] chars = content.toCharArray();
        int lenght = 0;
        for (char tempChar : chars) {
            boolean chinese = isChinese(tempChar);
            lenght += chinese ? 2 : 1;
        }
        return lenght;
    }

    public static void main(String[] args) {
        System.out.println("字符串长度：" + PrintUtils.getStringBite("ka7fy安静adg过，卡就hql"));
    }

    /**
     * 是否是中文
     *
     * @param c 待验证的字符
     * @return
     */
    public static boolean isChinese(char c) {
        Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);
        return ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS
                || ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS
                || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A
                || ub == Character.UnicodeBlock.GENERAL_PUNCTUATION
                || ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION
                || ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS;
    }

    /**
     * 拼接字符串
     *
     * @param contents 拼接内容集合
     * @return 拼接完成的字符串
     */
    private String splicing(String... contents) {
        if (contents.length > 0) {
            int[] lentns = new int[contents.length];
            int stringsLenth = 0;
            for (int i = 0; i < contents.length; i++) {
                int stringBite = getStringBite(contents[i]);
                lentns[i] = stringBite;
                stringsLenth += stringBite;
            }
            StringBuffer sb = new StringBuffer();
            if (stringsLenth >= 32) {
                for (String content : contents) {
                    sb.append(content);
                }
            } else {
                int spacesNumber = (32 - stringsLenth) / (contents.length - 1);
                for (int i = 0; i < contents.length; i++) {
                    sb.append(contents[i]);
                    if (i < contents.length - 1) {
                        for (int j = 0; j < spacesNumber; j++) {
                            sb.append(" ");
                        }
                    }
                }
            }
            return sb.toString();
        }
        return "";
    }

}
